<template>
  <!-- 导出Excel弹窗：visible由父组件控制，不直接修改 -->
  <el-dialog
      :model-value="visible"
      title="导出Excel配置"
      width="600px"
      draggable
      @close="handleDialogClose"
      :before-close="handleBeforeClose"
  >
    <div class="export-setting">
      <!-- 1. 自定义文件名 -->
      <el-form-item label="导出文件名" class="mb-4">
        <el-input
            v-model="localFileName"
            placeholder="请输入文件名（默认：表格数据）"
            maxlength="50"
        />
      </el-form-item>

      <!-- 2. 自定义导出字段（移除拖拽排序，与表格显示顺序一致） -->
      <el-form-item label="选择导出字段" class="mb-2">
        <el-text type="info" size="small">
          注：勾选需要导出的字段，顺序与表格当前显示顺序一致
        </el-text>
      </el-form-item>
      <!-- 普通列表渲染（移除VueDraggable组件） -->
      <el-checkbox-group v-model="localSelectedFields" class="checkbox-list">
        <div
            class="checkbox-item check-select"
            v-for="item in exportableColumns"
            :key="item.key"
        >
          <el-checkbox
              :label="item.key"
              :disabled="localSelectedFields.length <= 1 && localSelectedFields.includes(item.key)"
          >
            {{ item.title }} <!-- 多级表头显示格式：父标签-子标签（如"用户信息-姓名"） -->
          </el-checkbox>
        </div>
      </el-checkbox-group>
    </div>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleExportExcel">确认导出</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import * as XLSX from 'xlsx'
import { ElMessage } from 'element-plus'
import type { ElTable, TableColumnCtx } from 'element-plus'

// ---------------------- Props定义 ----------------------
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
    required: true
  },
  tableData: {
    type: Array,
    default: () => [],
    required: true
  },
  tableInstance: {
    type: Object as () => InstanceType<typeof ElTable>,
    required: true
  },
  defaultFileName: {
    type: String,
    default: '表格数据'
  },
  ignoreExportProp:{
    type:Array,
    default:()=>['__operate']
  },
  exportFuncMap:{
    type:Map
  }
})

// ---------------------- 事件定义 ----------------------
const emits = defineEmits([
  'update:visible',
  'export-success',
  'export-error'
])

// ---------------------- 本地状态 ----------------------
const localFileName = ref(props.defaultFileName)
const exportableColumns = ref<Array<{
  key: string
  title: string
  prop?: string
  parentProp?: string
  parentLabel?: string
  depth: number // 新增：记录列的层级深度，用于表头生成
}>>([])
const localSelectedFields = ref<string[]>([])

// ---------------------- 核心逻辑：解析列信息（修复多级表头） ----------------------
const initExportableColumns = () => {
  if (!props.tableInstance || !Array.isArray(props.tableInstance.columns)) {
    ElMessage.warning('表格实例异常，无法获取列配置信息')
    exportableColumns.value = []
    localSelectedFields.value = []
    return
  }

  const result: typeof exportableColumns.value = []

  // 递归解析并记录层级深度
  const recursiveParse = (
      cols: TableColumnCtx[],
      parentProp?: string,
      parentLabel?: string,
      depth = 1 // 新增：默认层级深度为1
  ) => {
    cols.forEach(col => {

      if(props.ignoreExportProp.includes(col.property) ){
        return
      }
      if (col.children && col.children.length > 0) {
        // 父列递归处理，深度+1
        recursiveParse(col.children, col.property, col.label, depth + 1)
      } else {
        const key = parentProp ? `${parentProp}-${col.property}` : col.property
        const title = parentLabel ? `${parentLabel}-${col.label}` : col.label
        result.push({
          key,
          title,
          prop: col.property,
          parentProp,
          parentLabel,
          depth // 记录当前列的层级深度
        })
      }
    })
  }

  recursiveParse(props.tableInstance.columns.filter(item=>item.property ))
  exportableColumns.value = result
  localSelectedFields.value = result.map(item => item.key)
}

watch(
    () => props.visible,
    (isShow) => {
      if (isShow) {
        initExportableColumns()
        localFileName.value = props.defaultFileName
      }
    },
    { immediate: true }
)

/**
 * 核心：处理Excel导出逻辑
 */
const handleExportExcel = () => {
  try {
    if (props.tableData.length === 0) {
      ElMessage.warning('暂无数据可导出')
      return
    }
    const selectedCols = exportableColumns.value.filter(item =>
        localSelectedFields.value.includes(item.key)
    )
    if (selectedCols.length === 0) {
      ElMessage.warning('请至少选择一个导出字段')
      return
    }

    // 修复1：计算表头总层级
    const maxDepth = Math.max(...selectedCols.map(col => col.depth), 1)
    const header: string[][] = Array.from({ length: maxDepth }, () => [])

    // 修复2：构建多级表头映射关系
    const parentMap = new Map<string, {
      start: number,
      end: number,
      row: number
    }>()

    // 修复3：正确填充表头数据
    selectedCols.forEach((col, colIndex) => {
      // 填充当前列的各级标题
      let currentDepth = col.depth
      let currentLabel = col.title

      // 从最深层开始填充
      header[currentDepth - 1][colIndex] = currentLabel

      // 向上级填充父标题
      let parentProp = col.parentProp
      let parentLabel = col.parentLabel
      let parentDepth = currentDepth - 1

      while (parentProp && parentLabel && parentDepth > 0) {
        if (!header[parentDepth - 1][colIndex]) {
          header[parentDepth - 1][colIndex] = parentLabel
        }

        // 记录父标题范围
        if (!parentMap.has(parentProp)) {
          parentMap.set(parentProp, {
            start: colIndex,
            end: colIndex,
            row: parentDepth - 1
          })
        } else {
          parentMap.get(parentProp)!.end = colIndex
        }

        // 继续向上查找
        const parentCol = selectedCols.find(c => c.prop === parentProp && !c.parentProp)
        parentProp = parentCol?.parentProp
        parentLabel = parentCol?.parentLabel
        parentDepth--
      }
    })

    // 修复4：生成合并配置
    const mergeRanges: XLSX.Range[] = []
    parentMap.forEach(({ start, end, row }) => {
      mergeRanges.push({
        s: { r: row, c: start },
        e: { r: row, c: end }
      })
    })

    // 构建导出数据（保持不变）
    const exportData = props.tableData.map(row => {
      return selectedCols.map(col => {
         let value=col.parentProp
            ? (row[col.parentProp as keyof typeof row]?.[col.prop as keyof any])
            : (row[col.prop as keyof typeof row])
        if(props.exportFuncMap?.has(col.prop)){
          value=props.exportFuncMap.get(col.prop)(value)
        }
        return value
      })
    })

    // 生成Excel文件
    const wsData = [].concat(header, exportData)
    const worksheet = XLSX.utils.aoa_to_sheet(wsData)
    worksheet['!merges'] = mergeRanges

    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

    const finalFileName = `${localFileName.value}_${Date.now()}.xlsx`
    XLSX.writeFile(workbook, finalFileName)

    ElMessage.success('Excel导出成功')
    emits('update:visible', false)
    emits('export-success', finalFileName)

  } catch (error) {
    ElMessage.error('Excel导出失败，请重试')
    emits('export-error', error)
  }
}

// ---------------------- 弹窗操作相关方法 ----------------------
const handleCancel = () => {
  emits('update:visible', false)
}

const handleDialogClose = () => {
  emits('update:visible', false)
}

const handleBeforeClose = (done: () => void) => {
  emits('update:visible', false)
  done()
}
</script>

<style scoped lang="scss">
.export-setting {
  padding: 10px 0;

  .checkbox-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    max-height: 300px;
    overflow-y: auto;
    padding-right: 8px;
    box-sizing: border-box;
  }

  .checkbox-item {
    padding: 6px 10px;
    border-radius: 4px;
    transition: background-color 0.2s ease;
    cursor: pointer;

    &:hover {
      background-color: #ecf5ff;
    }
  }
}
</style>
